package com.haiheng.module_main.fragment

import android.annotation.SuppressLint
import android.app.ScansManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.dialog.StandardDialog
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.DateUtils
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.library_base.utils.SPUtils
import com.haiheng.library_base.utils.SystemUtil
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.BookListAdapter
import com.haiheng.module_main.databinding.FragmentAssetInventoryBinding
import com.haiheng.module_main.mode.AssetInventoryViewModel
import com.haiheng.module_main.mode.BookInfoViewModel
import com.haiheng.module_main.mode.DeploymentViewModel

/**
 *
 * @Des: 资产盘点
 * @Author: hwz
 * @Date:2023/6/17 0017
 * @Version: 1.0
 */
class AssetInventoryFragment :RouterFragment() {
    private lateinit var binding: FragmentAssetInventoryBinding
    private val viewMode : BookInfoViewModel by viewModels()
    private lateinit var assetInventoryViewModel: AssetInventoryViewModel
    private val bookListAdapter = BookListAdapter()
    private var mScansManager: ScansManager? = null
    private lateinit var loadingDialog : LoadingDialog
    private val observer = Observer<MsgEvent> { msgEvent ->
        onMessageChange(msgEvent)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAssetInventoryBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun initView() {
        assetInventoryViewModel = AssetInventoryViewModel(viewMode)
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        binding.includeTile.tvTitle.setText("资产盘点")
        setInventoryTime()
        binding.includeTile.ivBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.includeTile.cbRignt.visibility = View.GONE
        binding.includeTile.cbRignt.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = true
        }

        binding?.rvBookList?.layoutManager = LinearLayoutManager(activity)
        binding?.rvBookList?.adapter = bookListAdapter
        bookListAdapter.setHidenCheck(true)
        initLisener()
        assetInventoryViewModel.getToltalNum()
    }

    fun setInventoryTime(){
        binding.tvInventoryTime.setText("最近一次盘点时间：${AppConstant.getLastInventoryTime()}")
    }

    private fun initLisener() {
        bookListAdapter.setOnItemClickListener(object : BaseAdapter.OnItemClickListener{
            override fun onItemClick(holder: BaseAdapter.ViewBindHolder, position: Int) {
                var bookInfoBean = bookListAdapter.getItem(position)
                bookListAdapter.notifyDataSetChanged()
            }
        })
        binding.btnReInventory.setOnClickListener {
            //重新盘点
            StandardDialog.newInstance().setTitle("是否确认重新盘点")
                .setContent("重新盘点将清除之前所有盘点记录\n请谨慎操作")
                .setOnDialogListener(object : StandardDialog.OnDialogClickListener{
                    override fun onCancel(dialog: StandardDialog) {
                        dialog.dismiss()
                    }

                    override fun onConfirm(dialog: StandardDialog) {
                        SPUtils.getInstance().put(AppConstant.SP_LAST_INVENTORY_TIME,"")
                        viewMode._bookListData.postValue(listOf())
                        assetInventoryViewModel.clearRecord()
                        setInventoryTime()
                        dialog.dismiss()
                    }
                }).show(childFragmentManager)
        }
        binding.btnFinishInventory.setOnClickListener {
            //结束盘点
            var cotent = "本次盘点${viewMode.bookListData.value?.size.toString()}本,总共已经盘点：${assetInventoryViewModel.areadyInventoryNum.value.toString()}"
            if (bookListAdapter.getData().size > 0){
                StandardDialog.newInstance().setTitle("是否结束盘点")
                    .setContent(cotent)
                    .setOnDialogListener(object : StandardDialog.OnDialogClickListener{
                        override fun onCancel(dialog: StandardDialog) {
                            dialog.dismiss()
                        }

                        override fun onConfirm(dialog: StandardDialog) {
                            SPUtils.getInstance().put(AppConstant.SP_LAST_INVENTORY_TIME,
                                DateUtils.getTime(System.currentTimeMillis()))
                            assetInventoryViewModel.addInventoryRecord()
                            setInventoryTime()
                            dialog.dismiss()
                        }
                    }).show(childFragmentManager)

            }else{
                ToastUtils.showShort("没有需要保存的盘点数据")
            }

        }
        binding.btnExportInventory.setOnClickListener {
            loadingDialog.setMessage("正在导出数据")
            loadingDialog.show()
//            ToastUtils.showShort("导出成功")
            assetInventoryViewModel.onExportExcel()
        }
    }

    override fun onResume() {
        super.onResume()
        observEven()
    }

    override fun onPause() {
        super.onPause()
        clearMsg()
        mScansManager?.persistMode = false
        mScansManager?.stopScan()
    }

    override fun initViewModel(): BaseViewModel? {
        viewMode.bookListData.observe(viewLifecycleOwner){
            binding.tvBookNum.setText("本次盘点数量：${it.size}")
            bookListAdapter.setNewData(it)

        }
        viewMode.showMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort(it)
            loadingDialog.hide()
        }
        viewMode._bookInfoByBarcode.observe(viewLifecycleOwner){

            assetInventoryViewModel.addBook(it)
        }
        viewMode._failBookInfoByBarcode.observe(viewLifecycleOwner){
            assetInventoryViewModel.addBook(it)
        }
        assetInventoryViewModel.areadyInventoryNum.observe(viewLifecycleOwner){
            binding.tvTotalInventoryNum.setText("总盘点数量:${it.toString()}")
        }

        return viewMode
    }

    private fun onMessageChange(msgEvent: MsgEvent?) {
        when (msgEvent?.code){
            MsgCode.MSG_SCANS_BARCODE->{
                if (FastClickUtil.isFaskMsg(msgEvent.msg,200)) return //两次相同消息太快这不处理
                val barcodeExists = viewMode._bookListData.value?.any { it.barCode == msgEvent.msg }
                if (barcodeExists == true) return
                assetInventoryViewModel.isAreadyInventory(msgEvent.msg)
//                viewMode.searchBookInfoByBarCode(msgEvent.msg)
            }
        }
    }

    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observe(this,observer)
        }
    }
    fun clearMsg(){
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
        }
    }

    @SuppressLint("WrongConstant")
    override fun initLoad() {
        var manager   = activity.getSystemService("scans")
        if (manager != null){
            mScansManager = manager as ScansManager
            mScansManager?.persistMode =true
        }
    }

}